import extend from 'extend'
import { modal } from 'vue-strap'
import { newMiniAd, showMsg } from '../../../vuex/action'

const validation = {
  ad(data) {
    for (let name in data) {
      if ((data[name] + '').length === 0) {
        return false
      }
    }
    return true
  }
}
const defaultAd = {
  title: '',
  location: '',
  allowExtend: 0
}

export default {
  name: 'MiniAdList',
  components: {
    'vue-modal': modal
  },
  data() {
    return {
      showNewAdModal: false,
      ad: extend(true, {}, defaultAd)
    }
  },
  vuex: {
    actions: {
      xShowMsg: showMsg,
      xNewMiniAd: newMiniAd
    }
  },
  methods: {
    resetAd() {
      this.ad = extend(true, {}, defaultAd)
    },
    newAd() {
      this.showNewAdModal = true
    },
    submit() {
      var ad = extend(true, {}, this.ad)
      ad.allowExtend = +ad.allowExtend

      var valid = validation.ad(ad)
      if (!valid) {
        return this.xShowMsg({
          type: 'danger',
          content: '* 标记的都是必填/必选项'
        })
      }

      this.xNewMiniAd(ad)
        .then(() => {
          this.resetAd()
          this.showNewAdModal = false
        })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    }
  }
}
